package com.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.app.common.Result;
import com.app.common.SystemConstant;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.BusinessService;
import com.app.service.IConsumptionOrderService;
import com.app.service.VerificationRecordService;
import com.app.utils.*;
import com.app.vo.AreaVo;
import com.app.vo.ConsumptionDivideConfigVo;
import com.app.vo.ConsumptionOrderVo;
import com.app.vo.ConsumptionVoucherVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import com.google.zxing.WriterException;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.app.common.SystemConstant.DEFAULT_PDF_SERVICE_URL;

/**
 * <p>
 * 消费多少送多少订单记录 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2024-07-21
 */
@Service
public class ConsumptionOrderServiceImpl extends ServiceImpl<ConsumptionOrderMapper, ConsumptionOrder> implements IConsumptionOrderService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ConsumptionOrderMapper consumptionOrderMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private ConsumptionDivideConfigMapper consumptionDivideConfigMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ConsumptionVoucherMapper consumptionVoucherMapper;
    @Autowired
    private ConsumptionVoucherShareMapper consumptionVoucherShareMapper;
    @Autowired
    private BusinessService businessService;

    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private VerificationRecordService verificationRecordService;


    static ThreadPoolExecutor cacheThreadPool = new ThreadPoolExecutor(1, 10,
            1, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());


    //生成兑换码 唯一值
    public String generateRandomCode(Integer length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // 包含大写字母和数字
        Random rnd = new Random();
        ConsumptionVoucher order; // 定义在do-while外部，但在循环内部赋值
        String uniqueCode;

        do {
            StringBuilder sb = new StringBuilder(length);
            for (int i = 0; i < length; i++) {
                sb.append(characters.charAt(rnd.nextInt(characters.length())));
            }
            uniqueCode = sb.toString();
            QueryWrapper<ConsumptionVoucher> qw = new QueryWrapper<>();
            qw.eq("verification_code", uniqueCode); // 使用uniqueCode作为查询条件
            order = consumptionVoucherMapper.selectOne(qw); // 在这里赋值
        } while (order != null); // 如果已存在，则重新生成

        return uniqueCode;
    }

    @Autowired
    private AliyunOSSUtils aliyunOSSUtils;
    //预约  消费多送订单
    @Override
    public Result reservationConsumptionOrder(ConsumptionOrder consumptionOrder, UserModel user) {

        //预约一次，未消费，不可再次预约
        QueryWrapper<ConsumptionOrder> qw = new QueryWrapper<>();
        qw.eq("user_id", user.getId());
        qw.eq("business_id", consumptionOrder.getBusinessId());
        qw.eq("status", 1);
        List<ConsumptionOrder> list = consumptionOrderMapper.selectList(qw);
        if (list.size() > 0) {
            return Result.error(201, "已有预约未消费订单！不可重复预约！");
        }
        //订单号
        String orderId = IdUtil.fastSimpleUUID();
        consumptionOrder.setOrderId(orderId);
        consumptionOrder.setStatus(1);
        //核销码
        String verification_code = generateRandomCode(8);
        consumptionOrder.setVerificationCode(verification_code);
        consumptionOrder.setCreateTime(CommonHelp.getNowTimestamp());
        consumptionOrder.setUserId(user.getId());
        consumptionOrder.setAreaId(user.getAreaId());
        consumptionOrder.setCityId(user.getCityId());

        // 生成二维码图片
        String verificationCodePath = System.getProperty("user.dir") + File.separator + "file" + File.separator + verification_code + ".png";
        QrCodeUtil.generate("classification=5#"+verification_code, 300, 300, FileUtil.file(verificationCodePath));
        String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + verification_code + ".png";
        consumptionOrder.setVerificationFilepath(fileURL);
        consumptionOrderMapper.insert(consumptionOrder);


        try{
            aliyunOSSUtils.objectStorageUploadFile(fileURL,FileUtil.getInputStream(verificationCodePath));
        }catch (Exception e)
        {

        }

        return Result.success("预约成功!");
    }



    //查询我的消费多送订单
    @Override
    public ConsumptionOrderVo queryConsumptionOrderList(Integer page, Integer limit,Integer userId,Integer status){
        Page<ConsumptionOrder> page1 = new Page<>(page, limit);
        QueryWrapper<ConsumptionOrder> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        if ( status != null){
            qw.eq("status", status);
        }
        qw.orderByDesc("create_time");
        Page<ConsumptionOrder> pageList = consumptionOrderMapper.selectPage(page1, qw);
        List<ConsumptionOrder> infoList = pageList.getRecords();
        for (ConsumptionOrder order : infoList){

            //获取商家信息
            Integer businessId = order.getBusinessId();
            BusinessModel businessInfo = businessMapper.selectById(businessId);

            //获取活动信息
            Integer activityId = order.getActivityId();
            ActivityModel activityInfo = activityMapper.selectById(activityId);

            order.setBusinessInfo(businessInfo);
            order.setActivityInfo(activityInfo);
        }
        long count = pageList.getTotal();
        ConsumptionOrderVo vo = new ConsumptionOrderVo();
        vo.setCount((int)count);
        vo.setList(infoList);
        return vo;
    }


    //查询我的卡券
    @Override
    public ConsumptionVoucherVo queryMyConsumptionVoucher(Integer page, Integer limit,Integer userId,String status){
        Page<ConsumptionVoucher> page1 = new Page<>(page, limit);
        QueryWrapper<ConsumptionVoucher> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        if (StringUtils.isNotEmpty(status)){
            qw.eq("status", status);
        }
        qw.orderByDesc("create_time");
        Page<ConsumptionVoucher> pageList = consumptionVoucherMapper.selectPage(page1, qw);
        List<ConsumptionVoucher> infoList = pageList.getRecords();
        ConsumptionVoucherVo vo = new ConsumptionVoucherVo();
        long count = pageList.getTotal();
        vo.setCount((int)count);
        vo.setList(infoList);
        return vo;
    }


    //定时器，每分钟执行
    //将到达使用日期的订单  改为 作废状态
    @Scheduled(cron = "0 * * * * ?")
    @Transactional
    public void updateConsumptionVoucher(){
        System.err.println("-------消费多送过期券码轮询开始--------");
//        @Update(" UPDATE tb_consumption_voucher " +
//                " SET status = 5 " +
//                " WHERE expiration_time < NOW() AND status NOT IN (4, 5); ")
//        consumptionVoucherMapper.UpdateExpireConsumptionVoucher();

        QueryWrapper<ConsumptionVoucher> consumptionVoucherQueryWrapper=new QueryWrapper<>();
        List<String> status=new ArrayList<>();
        status.add("4");
        status.add("5");
        consumptionVoucherQueryWrapper.notIn("status",status);
        consumptionVoucherQueryWrapper.lt("expiration_time", new Date());
        List<ConsumptionVoucher> consumptionVoucherList=this.consumptionVoucherMapper.selectList(consumptionVoucherQueryWrapper);
        if(CollectionUtil.isNotEmpty(consumptionVoucherList))
        {
            for (ConsumptionVoucher voucher:consumptionVoucherList)
            {
                voucher.setStatus(5);
                this.consumptionVoucherMapper.updateById(voucher);

                BusinessModel businessModel=this.businessMapper.selectById(voucher.getBusinessId());

                QueryWrapper<UserModel> qw_businessUser = new QueryWrapper<>();
                qw_businessUser.eq("phone", businessModel.getUserPhone());
                UserModel businessUser = userMapper.selectOne(qw_businessUser);
                if(businessUser==null)
                {
                    continue;
                }
                //增加益联券记录
                VoucherRecordModel voucherRecordModel_1 = new VoucherRecordModel();
                voucherRecordModel_1.setName("消费多少送多少兑换券失效返还");
                voucherRecordModel_1.setTypeName("兑换券失效返还");
                String amountVoucher_1 = "+" + voucher.getVoucher() + "券";
                voucherRecordModel_1.setVoucher(amountVoucher_1);
                voucherRecordModel_1.setUserId(businessUser.getId());
                voucherRecordModel_1.setCreateTime(CommonHelp.getNowTimestamp());
                voucherRecordModel_1.setVoucherType(1);
                voucherRecordModel_1.setVoucherAmount(voucher.getVoucher().doubleValue());
                voucherRecordModel_1.setWriteOff(1);
                voucherRecordMapper.insert(voucherRecordModel_1);

                this.adminUserService.accumulatVoucherForCurrentPlatformUser(2,voucher.getUserId(),"消费多少送多少兑换券失效反还商家",voucher.getVoucher());
            }
        }
        System.err.println("-------消费多送过期券码轮询结束--------");
    }

    @Autowired
    private AdminUserService adminUserService;
    public Result getBusinessInfoBycode(String verificationCode){
        QueryWrapper<ConsumptionVoucher> qw = new QueryWrapper<>();
        qw.eq("verification_code", verificationCode);
        ConsumptionVoucher order = consumptionVoucherMapper.selectOne(qw);
        return Result.success(order);
    }


    public Result queryWebConsumptionDivideConfig(Integer page, Integer limit,String businessName){
        Page<ConsumptionDivideConfig> page1 = new Page<>(page, limit);

        MPJQueryWrapper<ConsumptionDivideConfig> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.selectAll(ConsumptionDivideConfig.class);
        queryWrapper.select("t.*","case when b.business_name is null then '通用默认配置' else b.business_name end businessNameStr");
        queryWrapper.leftJoin("tb_business b on b.id = t.business_id");
        if (StringUtils.isNotBlank(businessName)){
            queryWrapper.like("b.business_name", businessName);
        }
        queryWrapper.orderByDesc("t.id");

        Page<ConsumptionDivideConfig> userModelPage = consumptionDivideConfigMapper.selectPage(page1, queryWrapper);
        List<ConsumptionDivideConfig> infoList = userModelPage.getRecords();
        ConsumptionDivideConfigVo vo = new ConsumptionDivideConfigVo();
        long count = userModelPage.getTotal();
        vo.setCount((int)count);
        vo.setList(infoList);
        return Result.success(vo);
    }


    public Result getWebConsumptionDivideConfigById(Integer id){
        QueryWrapper<ConsumptionDivideConfig> qw = new QueryWrapper<>();
        qw.eq("id", id);
        ConsumptionDivideConfig order = consumptionDivideConfigMapper.selectOne(qw);
        return Result.success(order);
    }


    public Result saveWebConsumptionDivideConfig(ConsumptionDivideConfig config,AdminUserModel userModel){
        if (null != config.getId()){//修改
            config.setUpdateUser(userModel.getId());
            config.setUpdateTime(CommonHelp.getNowTimestamp());
            consumptionDivideConfigMapper.updateById(config);
        }else {
            QueryWrapper<ConsumptionDivideConfig> qw = new QueryWrapper<>();
            qw.eq("business_id", config.getBusinessId());
            ConsumptionDivideConfig order = consumptionDivideConfigMapper.selectOne(qw);
            if (null != order){
                return Result.error(201, "该商家已有规则配置！");
            }

            config.setUserId(userModel.getId());
            config.setCreateTime(CommonHelp.getNowTimestamp());
            consumptionDivideConfigMapper.insert(config);
        }
        return Result.success("操作成功!");
    }


    @Override
    //核销  订单
    public Result writeOffConsumptionOrder(ConsumptionOrder consumptionOrder,String phone){


        //核销码
        String verificationCode = consumptionOrder.getVerificationCode();

        if (null != verificationCode){
            verificationCode = verificationCode.replaceAll("classification=5#","");
        }

        //消费金额
        BigDecimal orderMoney = consumptionOrder.getOrderMoney();
        //计算分成两张券的值
        BigDecimal userVoucherMoney = orderMoney.divide(BigDecimal.valueOf(2), BigDecimal.ROUND_HALF_UP);

        QueryWrapper<ConsumptionOrder> qw = new QueryWrapper<>();
        qw.eq("verification_code", verificationCode);
        ConsumptionOrder order = consumptionOrderMapper.selectOne(qw);

        if(order==null)
        {
            return Result.error(201, "订单不存在！");
        }


        /***********************核销后  扣减当前订单的人  的券**************************/
        QueryWrapper<UserModel> qw_orderUser = new QueryWrapper<>();
        qw_orderUser.eq("id", order.getUserId());
        UserModel order_userModel = userMapper.selectOne(qw_orderUser);
        BigDecimal voucher =  BigDecimal.valueOf(order_userModel.getVoucher());

        BigDecimal newVoucher_1 = voucher.subtract(orderMoney) ;
        if (newVoucher_1.compareTo(BigDecimal.ZERO) < 0){
            return Result.error(201, "用户券量不够抵扣！");
        }


        BusinessModel judgebusinessModel = businessService.getById(order.getBusinessId());
        if (judgebusinessModel == null) {
            return Result.error(201, "该商家不存在！");
        } else {
            if (judgebusinessModel.getBusinessStatus() == 2) {
                return Result.error(201, "该商家暂未营业！");
            }
            if (!phone.equals(judgebusinessModel.getUserPhone())) {
                return Result.error(201, "请使用该订单商家进行核销！");
            }
        }

        if (null == order){
            return Result.error(201, "兑换码不存在！");
        }
        if (1 != order.getStatus()){
            return Result.error(201, "兑换码不可用！");
        }
        //更新扣减券值
        order_userModel.setVoucher(newVoucher_1.doubleValue());
        userMapper.updateById(order_userModel);

        //增加益联券记录
        VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
        voucherRecordModel.setName("消费多少送多少订单消费成功");
        voucherRecordModel.setTypeName("消费订单");
        String amountVoucher = "-" + orderMoney + "券";
        voucherRecordModel.setVoucher(amountVoucher);
        voucherRecordModel.setUserId(order_userModel.getId());
        voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
        voucherRecordModel.setVoucherType(0);
        voucherRecordModel.setVoucherAmount(-orderMoney.doubleValue());
        voucherRecordModel.setWriteOff(1);
        voucherRecordMapper.insert(voucherRecordModel);

        /*****************再消费时  查询自己名下是否有需要激活的分成券 *******************/
        QueryWrapper<ConsumptionVoucher> qw_voucher = new QueryWrapper<>();
        qw_voucher.eq("type", "2");
        qw_voucher.eq("status", "2");
        qw_voucher.eq("user_id", order.getUserId());
        ConsumptionVoucher voucherInfo = consumptionVoucherMapper.selectOne(qw_voucher);
        if (null != voucherInfo){
            voucherInfo.setStatus(3);
            consumptionVoucherMapper.updateById(voucherInfo);
        }

        /*****************分享人再消费时  查询是否有被分享未激活的券 *******************/

        //如果有，则将券的状态改为已激活待使用状态
        ConsumptionVoucher shareVoucher = consumptionVoucherMapper.getConsumptionVoucherBySharedUserId(order.getUserId());
        if (null != shareVoucher){
            shareVoucher.setStatus(3);
            consumptionVoucherMapper.updateById(shareVoucher);
        }


        /*****************修改原消费多送订单的金额   修改状态*******************/
        //修改订单金额
        order.setOrderMoney(orderMoney);
        //修改订单状态为已核销
        order.setStatus(2);
        order.setUpdateTime(CommonHelp.getNowTimestamp());

        /*****************查询系统分成比例   表中为百分数*******************/
        //查询分成配置
        Integer businessId = order.getBusinessId();
        // 创建一个QueryWrapper来查询具有特定business_id的记录
        QueryWrapper<ConsumptionDivideConfig> qw_specificId = new QueryWrapper<>();
        qw_specificId.eq("business_id", businessId);

        // 尝试查询具有特定business_id的记录
        ConsumptionDivideConfig divideConfig = consumptionDivideConfigMapper.selectOne(qw_specificId);
        // 如果没有找到具有特定business_id的记录，则查询business_id为null的默认记录
        if (divideConfig == null) {
            // 创建一个新的QueryWrapper来查询business_id为null的记录
            QueryWrapper<ConsumptionDivideConfig> qw_default = new QueryWrapper<>();
            qw_default.eq("id",1);
            divideConfig = consumptionDivideConfigMapper.selectOne(qw_default);
        }

        // 将百分比转为小数
        // 商家 百分比分成比例
        BigDecimal businessProportionDecimal = divideConfig.getBusinessProportion().divide(new BigDecimal(100));
        //平台 百分比分成比例
        BigDecimal platformProportionDecimal = divideConfig.getPlatformProportion().divide(new BigDecimal(100));

        //券的过期天数
        Integer voucherExpirationDay = divideConfig.getVoucherExpirationDay();

        /*****************查询商家的用户信息  并且  修改商家用户的券值 （和原始值累加）*******************/
        // 计算商家应得的金额
        BigDecimal businessIncome = orderMoney.multiply(businessProportionDecimal);
        QueryWrapper<BusinessModel> qw_business = new QueryWrapper<>();
        qw_business.eq("id", businessId);
        BusinessModel businessModel = businessMapper.selectOne(qw_business);
        String businessUserPhone = businessModel.getUserPhone();
        QueryWrapper<UserModel> qw_businessUser = new QueryWrapper<>();
        qw_businessUser.eq("phone", businessUserPhone);
        UserModel businessUser = userMapper.selectOne(qw_businessUser);
        Double businessUserVoucher = businessUser.getVoucher();
        // 转换BigDecimal为Double并相加
        Double newVoucher = businessIncome.doubleValue() + businessUserVoucher;
        // 更新商家的券量
        businessUser.setVoucher(newVoucher);
        userMapper.updateById(businessUser);
        //更新消费多送订单中的商家分成值
        order.setBusinessIncome(businessIncome);


        //增加益联券记录
        VoucherRecordModel voucherRecordModel_1 = new VoucherRecordModel();
        voucherRecordModel_1.setName("消费多少送多少订单核销成功");
        voucherRecordModel_1.setTypeName("核销订单");
        String amountVoucher_1 = "+" + businessIncome + "券";
        voucherRecordModel_1.setVoucher(amountVoucher_1);
        voucherRecordModel_1.setUserId(businessUser.getId());
        voucherRecordModel_1.setCreateTime(CommonHelp.getNowTimestamp());
        voucherRecordModel_1.setVoucherType(1);
        voucherRecordModel_1.setVoucherAmount(businessIncome.doubleValue());
        voucherRecordModel_1.setWriteOff(1);
        voucherRecordMapper.insert(voucherRecordModel_1);





        /*****************用平台分成比例  分为两张券*******************/
        // 计算平台应得的金额
        BigDecimal platformIncome = orderMoney.multiply(platformProportionDecimal);

        //这是 平台计算比例后  需要生成的两张 券的 金额
        BigDecimal tempHalf = platformIncome.divide(BigDecimal.valueOf(2), BigDecimal.ROUND_HALF_UP);

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算配置的过期时间
        LocalDateTime oneWeekLater = now.plus(voucherExpirationDay, ChronoUnit.DAYS);
        Timestamp expirationTime = Timestamp.valueOf(oneWeekLater);
        //插入两张券
        ConsumptionVoucher consumptionVoucher = new ConsumptionVoucher();
        consumptionVoucher.setOrderId(order.getOrderId());
        consumptionVoucher.setVoucher(tempHalf);
        consumptionVoucher.setUserVoucher(userVoucherMoney);
        consumptionVoucher.setType("1");
        consumptionVoucher.setStatus(3);
        String verification_code = generateRandomCode(8);
        consumptionVoucher.setVerificationCode(verification_code);
        consumptionVoucher.setBusinessId(businessId);
        // 生成二维码图片
        String verificationCodePath_1 = System.getProperty("user.dir") + File.separator + "file" + File.separator + verification_code + ".png";
        QrCodeUtil.generate("classification=6#"+verification_code, 300, 300, FileUtil.file(verificationCodePath_1));
        String fileURL_1 = SystemConstant.DEFAULT_PDF_SERVICE_URL + verification_code + ".png";
        consumptionVoucher.setVerificationFilepath(fileURL_1);
        consumptionVoucher.setUserId(order.getUserId());
        consumptionVoucher.setCreateTime(CommonHelp.getNowTimestamp());
        consumptionVoucher.setExpirationTime(expirationTime);
        consumptionVoucherMapper.insert(consumptionVoucher);

        try{
            aliyunOSSUtils.objectStorageUploadFile(fileURL_1,FileUtil.getInputStream(verificationCodePath_1));
        }catch (Exception e)
        {

        }

        this.adminUserService.accumulatVoucherForCurrentPlatformUser(1,order_userModel.getId(),"消费多少送多少已激活兑换券平台暂存",consumptionVoucher.getVoucher());

        //插入 分享券
        consumptionVoucher.setType("2");
        consumptionVoucher.setStatus(2);
        verification_code = generateRandomCode(8);
        String verificationCodePath_2 = System.getProperty("user.dir") + File.separator + "file" + File.separator + verification_code + ".png";
        QrCodeUtil.generate("classification=6#"+verification_code, 300, 300, FileUtil.file(verificationCodePath_2));
        String fileURL_2 = SystemConstant.DEFAULT_PDF_SERVICE_URL + verification_code + ".png";
        consumptionVoucher.setVerificationFilepath(fileURL_2);
        consumptionVoucher.setVerificationCode(verification_code);
        consumptionVoucherMapper.insert(consumptionVoucher);

        try{
            aliyunOSSUtils.objectStorageUploadFile(fileURL_2,FileUtil.getInputStream(verificationCodePath_2));
        }catch (Exception e)
        {

        }

        this.adminUserService.accumulatVoucherForCurrentPlatformUser(1,order_userModel.getId(),"消费多少送多少待激活兑换券平台暂存",consumptionVoucher.getVoucher());

        Integer voucherId_2 = consumptionVoucher.getId();
        String fenxiang_verification_code = verification_code;

        /*****************更新原始订单的信息*******************/
        consumptionOrderMapper.updateById(order);

        //新增核销记录
        VerificationRecordModel verificationRecord = new VerificationRecordModel();
        verificationRecord.setBusinessId(order.getBusinessId());
        verificationRecord.setActivityName("消费多少送多少核销成功");
        verificationRecord.setOrderId(order.getOrderId());
        verificationRecord.setUserId(order.getUserId());
        verificationRecord.setPayAmount(order.getOrderMoney());
        verificationRecord.setContributeIntegral(0D);
        verificationRecord.setCreateTime(CommonHelp.getNowTimestamp());
        verificationRecord.setOrderId(order.getOrderId());
        verificationRecordService.save(verificationRecord);



        /*****************生成小程序分享二维码*******************/
        //异步 用线程池 生成二维码
        cacheThreadPool.submit(() -> {
            try {
                shareConsumerCoupon(fenxiang_verification_code,voucherId_2);
            }catch (Exception e){
                e.printStackTrace();
                System.err.println("-----------生成小程序分享二维码报错-------------------");
                System.err.println("An error occurred during operation: " + e.getMessage());
            }
        });

        /**************************************************/


        return Result.success("核销成功!");
    }


    //生成小程序 分享二维码
    public String shareConsumerCoupon(String verificationCode,Integer voucherId)throws Exception{

        String invitationCodeFileUrl = System.getProperty("user.dir") + File.separator + "wechat" + File.separator + verificationCode + ".png";
        WxQrCode.generateQrCode(invitationCodeFileUrl, "page_other/activity/merchant", WechatUtil.redisToken(), verificationCode);

        String filePath =  "/wechat/" + verificationCode + ".png";

        ConsumptionVoucher consumptionVoucher = new ConsumptionVoucher();
        consumptionVoucher.setId(voucherId);
        consumptionVoucher.setVoucherFilepath(filePath);
        consumptionVoucherMapper.updateById(consumptionVoucher);
        return filePath;
    }


    //接收  分享券
    @Override
    public Result handleShareConsumerCoupon(ConsumptionVoucher consumptionVoucher, UserModel userModel){
        //核销码
        String verificationCode = consumptionVoucher.getVerificationCode();

        QueryWrapper<ConsumptionVoucher> qw_business = new QueryWrapper<>();
        qw_business.eq("verification_code", verificationCode);
        ConsumptionVoucher voucherInfo = consumptionVoucherMapper.selectOne(qw_business);
        if (null == voucherInfo && "2".equals(voucherInfo.getType())){
            return Result.error(201, "消费券不存在！");
        }
        if (voucherInfo.getUserId().equals(userModel.getId())){
            return Result.error(201, "不可自己分享给自己！");
        }
        ConsumptionVoucherShare voucherShare = new ConsumptionVoucherShare();
        voucherShare.setOrderId(voucherInfo.getOrderId());
        voucherShare.setVoucherId(voucherInfo.getId());
        voucherShare.setVoucher(voucherInfo.getVoucher());
        voucherShare.setVerificationCode(verificationCode);
        voucherShare.setSharedUserid(userModel.getId());
        voucherShare.setCreateTime(CommonHelp.getNowTimestamp());
        consumptionVoucherShareMapper.insert(voucherShare);
        return Result.success("收到分享券!");
    }

    @Override
    public Result queryWebConsumptionOrderVoucherListById(String id){
        QueryWrapper<ConsumptionVoucher> qw = new QueryWrapper<>();
        qw.eq("order_id", id);
        List<ConsumptionVoucher> list = consumptionVoucherMapper.selectList(qw);
        return Result.success(list);
    }


    /**
     * 核销消费订单凭证
     *
     * @param consumptionVoucher 消费券
     * @param          区代 用户模型
     * @return {@link Result }
     *///核销  分成券
    @Override
    public Result writeOffConsumptionOrderVoucher(ConsumptionVoucher consumptionVoucher,UserModel qudailUser){
        //核销码
        String verificationCode = consumptionVoucher.getVerificationCode();

        if (null != verificationCode){
            verificationCode = verificationCode.replaceAll("classification=6#","");
        }

        QueryWrapper<ConsumptionVoucher> qw = new QueryWrapper<>();
        qw.eq("verification_code", verificationCode);
        ConsumptionVoucher voucher = consumptionVoucherMapper.selectOne(qw);
        if (null == voucher){
            return Result.error(201, "消费券不存在！");
        }
        String type = voucher.getType();
        if (("1".equals(type) && 3!= voucher.getStatus()) && ("2".equals(type) && 3!= voucher.getStatus())){
            return Result.error(201, "消费券不可用！");
        }
        if ( 4 == voucher.getStatus()){
            return Result.error(201, "消费券已使用！");
        }
        //更新使用时间
        voucher.setUsageTime(CommonHelp.getNowTimestamp());
        voucher.setStatus(4);//状态变更为已使用
        consumptionVoucherMapper.updateById(voucher);


        /*****************按照此次兑换码得金额  分成给区代*******************/
        //区代信息
//        UserModel qudailUser = userMapper.getAdminUserInfoByBusinessId(voucher.getBusinessId());
//        if (null != qudailUser){
            Double old_voucher = qudailUser.getVoucher();
            qudailUser.setVoucher(old_voucher + voucher.getVoucher().doubleValue());
            userMapper.updateById(qudailUser);


            //增加益联券记录
            VoucherRecordModel voucherRecordModel_1 = new VoucherRecordModel();
            voucherRecordModel_1.setName("消费多少送多少兑换券兑换成功");
            voucherRecordModel_1.setTypeName("兑换券");
            String amountVoucher_1 = "+" + voucher.getVoucher() + "券";
            voucherRecordModel_1.setVoucher(amountVoucher_1);
            voucherRecordModel_1.setUserId(qudailUser.getId());
            voucherRecordModel_1.setCreateTime(CommonHelp.getNowTimestamp());
            voucherRecordModel_1.setVoucherType(1);
            voucherRecordModel_1.setVoucherAmount(voucher.getVoucher().doubleValue());
            voucherRecordModel_1.setWriteOff(1);
            voucherRecordMapper.insert(voucherRecordModel_1);


//        }

        /*****************更新消费多送订单中的  赋能店分成值*******************/
        QueryWrapper<ConsumptionOrder> qw_order = new QueryWrapper<>();
        qw_order.eq("order_id", voucher.getOrderId());
        ConsumptionOrder order = consumptionOrderMapper.selectOne(qw_order);
        BigDecimal platformIncome = new BigDecimal(0);
        if (null != order.getPlatformIncome()){
            platformIncome = order.getPlatformIncome();
        }
        order.setPlatformIncome(platformIncome.add(voucher.getVoucher()));
        consumptionOrderMapper.updateById(order);

        this.adminUserService.accumulatVoucherForCurrentPlatformUser(2,order.getUserId(),"消费多少送多少兑换券区代核销",voucher.getVoucher());


        return Result.success("核销成功!");
    }


    public Result commentConsumptionOrder(ConsumptionOrder consumptionOrder){
        ConsumptionOrder order = consumptionOrderMapper.selectById(consumptionOrder.getId());
        if (!"1".equals(order.getStatus()) &&  null != order.getOrderReason() && 3== order.getStatus()){
            return Result.error(201, "当前订单已评价！");
        }
        if (!"2".equals(order.getStatus()) &&  null != order.getCommentstr()  && 4== order.getStatus()){
            return Result.error(201, "当前订单已取消！");
        }
        order.setStatus(3);
        order.setCommentstr(consumptionOrder.getCommentstr());
        consumptionOrderMapper.updateById(order);
        return Result.success("操作成功!");
    };


    public Result getClassificationConfig(){
        List<Map<String,Object>> list = consumptionOrderMapper.getClassificationConfig();
        return Result.success(list);
    }


    public Result queryWebConsumptionOrderList(Integer page,Integer limit, String beginTime, String endTim,String status){

        Page<ConsumptionOrder> page1 = new Page<>(page, limit);
        QueryWrapper<ConsumptionOrder> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTim)){
            qw.between("create_time", beginTime, endTim);
        }
        if (StringUtils.isNotEmpty(status)){
            qw.eq("status", status);
        }
        qw.orderByDesc("create_time");
        Page<ConsumptionOrder> pageList = consumptionOrderMapper.selectPage(page1, qw);
        List<ConsumptionOrder> infoList = pageList.getRecords();
        for (ConsumptionOrder order : infoList){

            Map<String,Object> cityInfo = consumptionOrderMapper.getCityInfo(order.getCityId(),order.getAreaId());
            if (cityInfo != null){
                order.setCityAreaName(cityInfo.get("city")+" / "+ cityInfo.get("area").toString());
            }

            //获取商家信息
            Integer businessId = order.getBusinessId();
            BusinessModel businessInfo = businessMapper.selectById(businessId);

            //获取活动信息
            Integer activityId = order.getActivityId();
            ActivityModel activityInfo = activityMapper.selectById(activityId);

            UserModel userModel = userMapper.selectById(order.getUserId());
            order.setUserInfo(userModel);
            order.setBusinessInfo(businessInfo);
            order.setActivityInfo(activityInfo);

            QueryWrapper<ConsumptionVoucher> qw_voucher = new QueryWrapper<>();
            qw_voucher.eq("order_id", order.getId());
            List<ConsumptionVoucher> vouchers = consumptionVoucherMapper.selectList(qw_voucher);
            order.setConsumptionVoucherList(vouchers);
        }
        ConsumptionOrderVo vo = new ConsumptionOrderVo();
        long count = pageList.getTotal();
        vo.setCount((int)count);
        vo.setList(infoList);
        return Result.success(vo);
    };

}
